﻿using MQTTnet;
using MQTTnet.Protocol;
using System.Buffers;
using System.Text;

namespace ZX.MQTTClient
{
    internal class Program
    {
        private static IMqttClient mqttClient;

        static async Task Main(string[] args)
        {
            await Connect();

            Console.ReadKey();
        }

        private static async Task Connect()
        {
            // 连接到MQTT服务器
            #region 连接到MQTT服务器
            MqttClientFactory mqttFactory = new MqttClientFactory();
            mqttClient = mqttFactory.CreateMqttClient();
            MqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder()
                .WithClientId("ZX001")
                .WithTcpServer("127.0.0.1", 1883)
                .WithCredentials("admin", "123456")
                .WithCleanSession(false)
                .Build();

            MqttClientConnectResult connectResult = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
            Console.WriteLine(($"ZX001,连接状态:{connectResult.ResultCode.ToString()}"));
            #endregion

            #region 订阅
            // 订阅的主题
            string topic = "Test/#";
            try
            {
                // 添加接收订阅主题的消息
                mqttClient.ApplicationMessageReceivedAsync += e =>
                {

                    ReadOnlySequence<byte> msgArray = e.ApplicationMessage.Payload;
                    var msg = Encoding.UTF8.GetString(msgArray);
                    //var msg = BitConverter.ToString(msgArray.ToArray()).Replace("-"," "); // 转换为十六进制字符串

                    Console.WriteLine($">>> 收到消息: {msg},来自客户端:{e.ClientId},主题:{e.ApplicationMessage.Topic}");

                    return Task.CompletedTask;
                };


                // 订阅主题
                await mqttClient.SubscribeAsync(new MqttClientSubscribeOptionsBuilder()
                    .WithTopicFilter(topic, MqttQualityOfServiceLevel.AtMostOnce)
                    .Build());

                Console.WriteLine($"订阅主题:{topic}成功！");
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            #endregion

            #region 发布消息
            // 负载消息
            string payload = $"Hello,everyone-{DateTime.Now}";
            //byte[] bytes = new byte[] { 0x01, 0x02, 0x03, 0x04 };
            MqttApplicationMessage messageApplication = new MqttApplicationMessageBuilder()
                .WithTopic("Test/1/2/c/d")
                .WithPayload(payload)  // 直接发送字符串    //.WithPayload(bytes)  // 发送字节数组
                .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
                .WithRetainFlag(false)
                .Build();

            await mqttClient.PublishAsync(messageApplication, CancellationToken.None);
            #endregion

        }
    }
}
